<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button type="primary" icon="el-icon-plus" @click="addTrademark">添加</el-button>
      </div>
      <div>
        <el-table border :data="tableData" style="width: 100%">
          <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>
          <el-table-column prop="tmName" label="品牌名称" width="180"></el-table-column>
          <el-table-column label="品牌Logo">
            <template #default="{ row }">
              <el-image :src="row.logoUrl" :lazy="true" style="height: 60px"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
            <el-button type="warning" icon="el-icon-edit" size="mini" @click="UpdateTrademark(row)">修改</el-button>
            <el-button type="danger" icon="el-icon-edit-outline" size="mini"  @click="deleteTrademark(row.id)">删除</el-button>
          </template>
          </el-table-column>
        </el-table>
        <!-- 分页列表 -->
        <el-pagination
          :current-page="page"
          :page-size="limit"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[3, 5, 7, 9]"
          layout="total,sizes,prev,pager,next,jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>
    <!-- :visible.sync控制对话框显示或者隐藏 -->
    <el-dialog title="添加品牌" :visible.sync="dialogFormVisible" width="60%">
      <el-form :model="newTrademark" :rules="rules" ref="ruleForm" label-width="100px" size="small">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input autocomplete="off" v-model="newTrademark.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action='`${baseUrl}/admin/product/upload`'
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="newTrademark.logoUrl" :src="newTrademark.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="AddTrademark">确 定</el-button>
      </div>
    </el-dialog>
    <div>
    <!--修改页面  -->
  </div>
  </div>

</template>

<script>
import { requesTrsdemarkPageList
  ,requestAddTrademark 
  ,requestUpdateTrademark,
  requestDeleteTrademark,
} from "@/api/trademark";

export default {
  name: "Trademark",

  data() {
      //自定义表单校验规则
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请上传图片'));
        } 
          callback();
        
      };


    return {
      page: 1,
      limit: 5,
      total: 0,
      tableData: [],
      // dialogImageUrl: "",
      // 控制对话框显示或者隐藏的属性
      dialogFormVisible: false,
      baseUrl:'',
      newTrademark:{
        tmName:'',
        logoUrl:'',
        id:0
      },
      rules:{
        tmName:[
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        logoUrl:[
          { validator: validatePass, trigger: 'blur' }
        ]
      }
    };
  },

  mounted() {
    this.getPageList();
    this.baseUrl = process.env.VUE_APP_BASE_API
  },
  methods: {
    async getPageList() {
      const result = await requesTrsdemarkPageList(this.page, this.limit);
      // 点击它触发事件，然后列表也会更新
      this.tableData = result.data.records;
      this.total = result.data.total;
    },
    handleSizeChange(val) {
      this.limit = val;
      this.getPageList();
    },
    handleCurrentChange(val) {
      // console.log("val",val);
      this.page = val;
      this.getPageList();
    },
    // // 点击添加品牌的按钮
    addTrademark() {
      this.newTrademark = {
        tmName:'',
        logoUrl:'',
        id:0
      }
      // 显示对话框
      this.dialogFormVisible = true;
    },
    // 新增某一个品牌
    async AddTrademark(){
      if(this.newTrademark.id){
      await requestUpdateTrademark(this.newTrademark)
       this.$message.success('修改品牌成功');
      }else{
        await requestAddTrademark(this.newTrademark)
        this.$message.success('新增品牌成功');
      }
      
      //重新发送请求刷新页面
      this.getPageList();
      this.dialogFormVisible = false;
    },

    // 修改某一个品牌
    async UpdateTrademark(row){
      // console.log(row,8888)
      this.newTrademark= row
      //修 改后重新刷新页面
      // this.getPageList();
      // 弹窗的显示
      this.dialogFormVisible = true;
    },

    //删除逻辑
     deleteTrademark(id){
      //弹框
      this.$confirm(`你确定删除${id.tmName}?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(async() => {
          
          //向服务器发送请求
           await requestDeleteTrademark(id)
           console.log(id,14475);
            //重新发送请求刷新页面
          this.getPageList();
          this.dialogFormVisible = false;
      
          // 用户点击确定的时候会触发
          this.$message({
          type: 'success',
          message: '删除成功!'
          });
          this.page= this.tableData.length>1?this.page:this.page-1
          //再次获取品牌列表数据
          this.getPageList();
       
        }).catch(() => {
          // 用户点击取消的时候会触发
          this.$message({
            type: 'info',
            message: '点错了吧'
          });          
        });
    },

    //这个是上传和图片的逻辑
    handleAvatarSuccess(res, file) {
        this.newTrademark.logoUrl = URL.createObjectURL(file.raw);
        console.log(!!this.newTrademark.logoUrl,99999)
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      //表单校验
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            alert('submit!');
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    
  },
  watch:{
    'newTrademark.tmName'(){
      console.log(1111);
      this.$refs.ruleForm.clearValidate()
      
    }
  }

};

// 表单校验规则
// 自定义表单规则函数


</script>

<style scoped lang="scss">
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  margin: 30px;
}


</style>

<style lang="scss">
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>